package com.cloudeasy.post.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.post.dao.mapper.PostCollectMapper;
import com.cloudeasy.post.po.PostCollect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PostCollectService extends ServiceImpl<PostCollectMapper, PostCollect> {
    private final PostService postService;

    @Autowired
    public PostCollectService(@Lazy PostService postService) {
        this.postService = postService;
    }

    /**
     * 收藏
     *
     * @param userId 用户Id
     * @param postId 帖子Id
     * @return {@link Boolean}
     */
    public Boolean collect(String userId, String postId) {
        if (this.getOne(wrapper(userId, postId)) != null) {
            throw new CloudEasyException(ResultCodeEnum.REPEAT_ERROR);
        }
        postService.collect(postId);
        PostCollect postCollect = PostCollect.builder().userId(userId).postId(postId).build();
        return this.save(postCollect);
    }

    /**
     * 取消收藏
     *
     * @param userId 用户Id
     * @param postId 帖子Id
     * @return {@link Boolean}
     */
    public Boolean removeCollect(String userId, String postId) {
        PostCollect postCollect = this.getOne(wrapper(userId, postId));
        if (postCollect == null) {
            throw new CloudEasyException(ResultCodeEnum.REPEAT_ERROR);
        }
        postService.removeCollect(postId);
        return this.remove(wrapper(userId, postId));
    }

    /**
     * 获取某用户的所有关注
     *
     * @param userId 用户Id
     * @return {@link List<PostCollect>}
     */
    public List<PostCollect> listByUserId(String userId) {
        return this.list(wrapper(userId, null));
    }

    /**
     * 构建wrapper
     *
     * @param userId 用户Id
     * @param postId 帖子Id
     * @return {@link QueryWrapper<PostCollect>}
     */
    public QueryWrapper<PostCollect> wrapper(String userId, String postId) {
        QueryWrapper<PostCollect> queryWrapper = new QueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq("user_id", userId);
        }
        if (postId != null) {
            queryWrapper.eq("post_id", postId);
        }
        return queryWrapper;
    }

    /**
     * 根据帖子Id删除记录
     *
     * @param postId 帖子Id
     * @return {@link Boolean}
     */
    public Boolean removeByPostId(String postId) {
        return this.remove(wrapper(null, postId));
    }
}
